//
//  UIImageView+Gif.m
//  KKThread
//
//  Created by Mac mini on 16/2/25.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "UIImageView+Gif.h"

@implementation UIImageView (Gif)

- (void)kk_loadingGifImageWithPath:(NSString *)path {
    
    NSData *imageData = [NSData dataWithContentsOfFile: path];
    [self kk_loadingGifImageWithData: imageData];
}

- (void)kk_loadingGifImageWithURL:(NSURL *)imageURL {
    
    if (imageURL == nil) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *imageData = [NSData dataWithContentsOfURL: imageURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf kk_loadingGifImageWithData: imageData];
        });
    });
}

#pragma mark - Private methods

- (void)kk_loadingGifImageWithData:(NSData *)imageData {
    
    if (imageData == nil) {
        return;
    }
    
    CGImageSourceRef cImageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
    size_t imageCount = CGImageSourceGetCount(cImageSource);
    NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity: imageCount];
    NSMutableArray *times = [[NSMutableArray alloc] initWithCapacity: imageCount];
    NSMutableArray *keyTimes = [[NSMutableArray alloc] initWithCapacity: imageCount];
    
    CGSize size;
    float totalTime = 0;
    for (size_t i = 0; i < imageCount; i++) {
        
        CGImageRef cgimage = CGImageSourceCreateImageAtIndex(cImageSource, i, NULL);
        [images addObject:(__bridge id)cgimage];
        CGImageRelease(cgimage);
        
        NSDictionary *properties = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(cImageSource, i, NULL);
        NSDictionary *gifProperties = [properties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
        NSString *gifDelayTime = [gifProperties valueForKey:(__bridge NSString* )kCGImagePropertyGIFDelayTime];
        [times addObject:gifDelayTime];
        totalTime += [gifDelayTime floatValue];
        
        size.width = [[properties valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
        size.height = [[properties valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
    }
    
    float currentTime = 0;
    for (size_t i = 0; i < times.count; i++) {
        float keyTime = currentTime / totalTime;
        [keyTimes addObject:[NSNumber numberWithFloat:keyTime]];
        currentTime += [[times objectAtIndex:i] floatValue];
    }
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    [animation setValues:images];
    [animation setKeyTimes:keyTimes];
    animation.duration = totalTime;
    animation.repeatCount = HUGE_VALF;
    [self.layer addAnimation:animation forKey:@"gifAnimation"];
    
}

@end
